﻿using System;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Common.DataAnnotations;

namespace Common.MQ
{
    /// <summary>
    /// 消息队列消费者
    /// </summary>
    public abstract class MQConsumerBase : IDisposable
    {
        private List<IMessageHandler> Handlers;
        /// <summary>
        /// 消息队列消费者
        /// </summary>
        /// <param name="handlers"></param>
        public MQConsumerBase(List<IMessageHandler> handlers)
        {
            this.Handlers = handlers;
        }
        //protected List<ConsumerSpec> consumerSpecs = new List<ConsumerSpec>();
        /// <summary>
        /// 开启消费者监听
        /// </summary>
        public void Start()
        {
            ConnectToListen();
        }
        /// <summary>
        /// 连接服务器并监听消息
        /// </summary>
        protected abstract void ConnectToListen();
        /// <summary>
        /// 释放链接
        /// </summary>
        public void Dispose()
        {
            this.ReleaseResources();
        }
        /// <summary>
        /// 释放资源
        /// </summary>
        protected virtual void ReleaseResources()
        {

        }
        /// <summary>
        /// 获取匹配的处理程序
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        protected List<IMessageHandler> GetMatchHandlers(string typeName)
        {
            if (string.IsNullOrEmpty(typeName))
            {
                return null;
            }
            return Handlers.FindAll(x => x.DataType.FullName == typeName);
        }
        ///// <summary>
        ///// 添加消费者
        ///// </summary>
        ///// <param name="queue"></param>
        ///// <param name="handlers"></param>
        //public void AddConsumer(QueueSpec queue, params IMessageHandler[] handlers)
        //{
        //    this.consumerSpecs.Add(new ConsumerSpec { Handlers = handlers, Queue = queue });
        //}
        //protected class ConsumerSpec
        //{
        //    public QueueSpec Queue { get; set; }
        //    public IMessageHandler[] Handlers { get; set; }
        //}
    }
}
